package org.misty.blog.controller;

import org.misty.blog.exception.NotFoundException;
import org.misty.blog.po.Article;
import org.misty.blog.po.Comment;
import org.misty.blog.service.ArticleService;
import org.misty.blog.service.CommentService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;
import java.util.Optional;

@Controller
public class CommentController {
    private final ArticleService articleService;
    private final CommentService commentService;

    public CommentController(ArticleService articleService, CommentService commentService) {
        this.articleService = articleService;
        this.commentService = commentService;
    }

    @GetMapping("/comments/{articleId}")
    public String comments(@PathVariable Long articleId, Model model) {
        List<Comment> comments = commentService.listCommentByArticleId(articleId);
        model.addAttribute("comments", comments);
        return "blog::commentList";
    }

    @PostMapping("/comments")
    public String post(Comment comment) {
        Long articleId = comment.getArticle().getId();
        Optional<Article> articleOpt = articleService.getArticle(articleId);
        articleOpt.orElseThrow(() -> new NotFoundException("您所评论的文章不存在"));
        comment.setArticle(articleOpt.get());
        commentService.saveComment(comment);
        return "redirect:/comments/" + articleId;
    }
}
